package com.jingxuan.service.impl;

import com.jingxuan.common.constant.RedisKeyConstants;
import com.jingxuan.common.exception.BusinessException;
import com.jingxuan.common.result.ResultCode;
import com.jingxuan.dto.request.UserLoginRequest;
import com.jingxuan.dto.response.LoginResponse;
import com.jingxuan.entity.Role;
import com.jingxuan.entity.User;
import com.jingxuan.mapper.RoleMapper;
import com.jingxuan.service.AuthService;
import com.jingxuan.service.UserService;
import com.jingxuan.util.JwtUtil;
import com.jingxuan.util.MD5Util;
import com.jingxuan.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 认证服务实现类
 */
@Slf4j
@Service
public class AuthServiceImpl implements AuthService {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private RoleMapper roleMapper;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private RedisUtil redisUtil;
    
    @Value("${jwt.expiration}")
    private Long jwtExpiration;
    
    @Override
    public LoginResponse login(UserLoginRequest request) {
        // 根据手机号查询用户
        User user = userService.getUserByPhone(request.getPhone());
        if (user == null) {
            throw new BusinessException(ResultCode.LOGIN_FAILED, "用户不存在");
        }
        
        // 校验账号状态（0:禁用 1:启用）
        // status为null时默认为启用，status为0时禁用
        log.info("用户登录校验，userId: {}, phone: {}, status: {}", user.getId(), user.getPhoneNumber(), user.getStatus());
        if (user.getStatus() != null && user.getStatus().equals(0)) {
            log.warn("用户账号已被封禁，拒绝登录，userId: {}", user.getId());
            throw new BusinessException(ResultCode.USER_DISABLED, "账号已被封禁，请联系管理员");
        }

        // 验证密码
        boolean isPasswordValid = MD5Util.verify(user.getPwd(), request.getPassword());
        if (!isPasswordValid) {
            throw new BusinessException(ResultCode.LOGIN_FAILED, "密码错误");
        }
        
        // 获取用户角色
        List<Role> roles = roleMapper.selectByUserId(user.getId());
        String rolesStr = roles.stream()
                .map(Role::getRoleName)
                .collect(Collectors.joining(","));
        
        // 生成Token
        String token = jwtUtil.generateToken(user.getId(), user.getUserName(), rolesStr);
        
        // 将Token存入Redis（过期时间与JWT一致）
        String redisKey = RedisKeyConstants.getTokenKey(user.getId());
        redisUtil.set(redisKey, token, jwtExpiration, TimeUnit.MILLISECONDS);
        
        // 构建响应
        LoginResponse response = new LoginResponse();
        response.setToken(token);
        response.setUserId(user.getId());
        response.setUserName(user.getUserName());
        response.setPhone(user.getPhoneNumber());
        response.setIcon(user.getAvatar());
        response.setBirthdate(user.getBirthdate());
        response.setPreferences(new ArrayList<>()); // TODO: 从用户偏好表获取
        
        log.info("用户登录成功，userId: {}, roles: {}", user.getId(), rolesStr);
        return response;
    }
    
    @Override
    public void logout(Long userId) {
        // 从Redis中删除Token
        String redisKey = RedisKeyConstants.getTokenKey(userId);
        redisUtil.delete(redisKey);
        
        log.info("用户登出成功，userId: {}", userId);
    }
}

